// PerfTest1.java

package com.ibm.tspaces.examples.simple;

import  java.util.*;
import  java.text.*;
import  java.io.*;
import  com.ibm.tspaces.*;
import  com.ibm.tspaces.query.*;
import  com.ibm.tspaces.server.*;

/*
**  Licensed Materials - Property of IBM
**
**  (C) COPYRIGHT IBM Corp. 1996, 1997  All rights reserved
**
**  US Government Users Restricted Rights - Use, duplication or
**  disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
**
**/
/**
** This class implements a very simple performance test 
** of TupleSpace.
** We will write "num" tuples and then take "num" tuples 
**
** Command line parameters:
**   
**  java com.ibm.spaces.examples.simple.PerfTest1 [options]
**    -h hostname      Host name for server (localhost)
**         If hostname "Local" use LocalCmdImpl
**    -s               Use SmallDB support  (MMDB)
**    -np              Specify non persistent  (Persistent)
**    -fifo            Specify FIFO option
**    number           Number of Tuples to write ( 100 )
**
**  

** @see TupleSpace
** @version $Revision: 2.1.2.2 $ $Date: 2000/02/05 14:50:43 $
** @author John Thomas
*/


public class PerfTest1 {
	
	public static void usage() {
   System.out.println("** Command line parameters:");
   System.out.println("**");   
   System.out.println("**  java com.ibm.spaces.examples.simple.PerfTest1 [options]");
   System.out.println("**    -h hostname      Host name for server (localhost)");
   System.out.println("**         If -h Local then run with Local server");
   System.out.println("**    -s               Use SmallDB support  (MMDB)");
   System.out.println("**    -np              Specify non persistent  (Persistent)");
   System.out.println("**    -fifo            Specify FIFO option");
   System.out.println("**    number           Number of Tuples to write ( 100 )");

    
  }
  
  
  public static void main( String argv[] ) {
  	String  tsName = null;
  	String	host	=	"localhost";
        
	  ConfigTuple	config = new ConfigTuple();
    boolean mmdb = true;
    boolean persistent = true;
    boolean fifo = false;
    int     num  = 100;
    TSServer tsServer = null;
    try {
	            
      for (int i=0; i< argv.length; i++) {
        if (argv[i].equals("?") ) {
          usage();
          return;
        } else if (argv[i].equals("-s") ) 
          mmdb = false;         
        else if (argv[i].equals("-D") )
          Debug.setDebugOn(true);
        else if (argv[i].equals("-h") )
          host = argv[++i];
        else if (argv[i].equals("-np") )   // non persistent
          persistent = false;
        else if (argv[i].equals("-fifo") )   // FIFO
          fifo = true;  
        else if (argv[i].startsWith("-")) {
          usage();
          return;
        } else {
          // if numeric than count
          try {
            num = Integer.parseInt( argv[i] );        
  
          } // try
          catch( NumberFormatException nfe ) {
            // Must be a host name
            host = argv[i];          
    
          } // catch
        }
      } // for
      config = new ConfigTuple();
      if ( mmdb ) {
        config.setOption(ConfigTuple.TSDBTYPE,TupleSpace._DBTYPE_MMDB);
        tsName = "mmdb";
      } else {
         config.setOption(ConfigTuple.TSDBTYPE,TupleSpace._DBTYPE_SMALLDB);
         tsName = "smalldb";
      }
      if (! persistent) {
        tsName = tsName+"NP";  
         config.setOption(ConfigTuple.PERSISTENCE,Boolean.FALSE);
      }
      if (fifo) {
        tsName = tsName+"FIFO";  
         config.setOption(ConfigTuple.FIFO,Boolean.TRUE);
      }

      
    } catch(Exception e) {
        Debug.out(e);
    }
    
    // 
    // OK we parsed the command line.  
    TupleSpace.appletEnvironment(true);  
    try {  
      
      // Run test with client and server in same Java VM
      if ( host.equals("Local") ) {  
        //TSServer ts = new TSServer( port, checkpointDir, freshStart, checkpointInterval, configFile );
        boolean freshStart = true;
        String configFile = null;  // future?
        tsServer = new TSServer(TupleSpace.DEFAULTPORT , null, freshStart, -1, configFile);
        
        Thread serverThread = new Thread( tsServer, "TSServer" );
        serverThread.start();
        Thread.sleep(1000);
        //Debug.setDebugOn(true);
        TupleSpace.setTSCmdImpl("com.ibm.tspaces.TSCmdLocalImpl");
      }

        
	     System.out.println("Access Space@Server "+tsName+"@"+host);
		
	     TupleSpace ts = new TupleSpace(tsName,host,config);
       ts.deleteAll();
        // Turn on Structure index
        //ConfigTuple ct = new ConfigTuple(ConfigTuple.STRUCT_INDEX);
        //Tuple index = ts.indexCreate(ConfigTuple.STRUCT_INDEX,String.class,ct,true);
        // write some arbitrary tuples to the space.
     /***
        for (int i=0; i< num; i++) {          
          Tuple testx = new Tuple("TestX","X#"+i,"some data","more data");
          ts.write(testx);
        }
     ****/   
        System.out.println("Start test");
	      SuperTuple tup = null;
	
	      long starttime = System.currentTimeMillis();
		    long totaltime;
	      
	
	      // Write test1 - simple tuple with 2 fields
	      Tuple test1;
        //test1 = new Tuple("Test1","#");

	      starttime = System.currentTimeMillis();
	      	
	      for (int i=0; i< num; i++) {	      	
          test1 = new Tuple("Test1","#"+i);
	      	ts.write(test1);
	      
	      }
	      totaltime = System.currentTimeMillis() - starttime;
	      System.out.println(num +" Tuples written to TS.  Time : " + totaltime);
       
       
        
        // Write test2 - simple tuple with 1 indexed field
		    Tuple test2 = null;
		    starttime = System.currentTimeMillis();
	      
	      for (int i=0; i< num; i++)  {
          String str = "#"+i;
          test2 = new Tuple("Test2",new Field("Index",str));
          ts.write(test2);
        }
	      totaltime = System.currentTimeMillis() - starttime;
	      System.out.println( num +" Tuples(Indexed) written to TS.  Time : " + totaltime);
	
        // Write test2a - simple tuple with StringBuffer
        Tuple test2a = null;
        starttime = System.currentTimeMillis();        
        for (int i=0; i< num; i++)  {           
          StringBuffer str = new StringBuffer("#"+i);
          test2a = new Tuple("Test2",new Field(str));
          ts.write(test2a);
        }
        totaltime = System.currentTimeMillis() - starttime;
        System.out.println( num +" Tuples (Not cloneable) written to TS.  Time : " + totaltime);

	
	      // Scan what was just written
	      Tuple template1 = new Tuple("Test1",new Field(String.class));
	      
	
	      starttime = System.currentTimeMillis();
	      Tuple tupleset = ts.scan(template1);
	      int cnt = 0;
	      if ( tupleset != null) {
	          for( Enumeration e = tupleset.fields(); e.hasMoreElements(); ) {
	              Field f = (Field)e.nextElement();
	              tup = (Tuple)f.getValue();
	              cnt++;
	          }      
	      }
	      	
	      totaltime = System.currentTimeMillis() - starttime;
	      System.out.println(cnt + " Tuples read(with scan) from TS. Time : " + totaltime);
	      
        Tuple template2 = new Tuple("Test2",new Field(String.class));
        Range range = new Range(null,null);
        IndexQuery iq = new IndexQuery("Index",range);       
        MatchQuery mq = new MatchQuery(template2);
        Tuple aq =new Tuple(iq,mq);
       

		    starttime = System.currentTimeMillis();
		    cnt = 0;
	      tupleset = ts.scan(aq);
	      if ( tupleset != null) {
	          for( Enumeration e = tupleset.fields(); e.hasMoreElements(); ) {
	              Field f = (Field)e.nextElement();
	              tup = (Tuple)f.getValue();
                Debug.out(tup);
	              cnt++;             
	          }      
	      }
	
	      totaltime = System.currentTimeMillis() - starttime;
	      System.out.println(cnt + " Tuples read(index scan) from TS. Time : " + totaltime);
	      
        
        // measure 10 reads using template match.
        starttime = System.currentTimeMillis();
        cnt = 0;
        for (int i=num/2; i< num/2+num/10; i++)  {
          Tuple template2a = new Tuple(new Field(String.class),"#"+i);
          test2 = new Tuple(template2a);      
          Tuple result = ts.read(template2a);
          //Debug.out(0,result);
          cnt++;
        }

        
        totaltime = System.currentTimeMillis() - starttime;
        System.out.println(cnt + " Tuples read(Template Match) from TS. Time : " + totaltime);
        
        // measure 10 reads using Index query.
        starttime = System.currentTimeMillis();
        cnt = 0;
        for (int i=num/2; i< num/2+num/10; i++)  {
          Tuple template2a = new Tuple(new IndexQuery("Index","#"+i));
          test2 = new Tuple(template2a);      
          Tuple result = ts.read(template2a);
          //Debug.out(0,result);
          cnt++;
        }

        
        totaltime = System.currentTimeMillis() - starttime;
        System.out.println(cnt + " Tuples read(indexQuery)from TS. Time : " + totaltime);
        

        
	      // Measure using take
	      starttime = System.currentTimeMillis();
        Tuple template1t = new Tuple("Test1",new Field(String.class));

	      for (int i=0; i < num; i++) { 
          template1t.getField(1).setValue("0"+i);
	      	tup = ts.take(template1t);
          Debug.out("Taken="+tup);	      
	      }
	      	
	      totaltime = System.currentTimeMillis() - starttime;
	      System.out.println(num +" Tuples taken from TS. Time : " + totaltime);
	      
        // measure take using index Query
		    starttime = System.currentTimeMillis();
        IndexQuery iqtake = null;
	      for (int i=0; i < num; i++) {
          iqtake = new IndexQuery("Index","#"+i);
 
          tup = ts.take(iqtake);
          Debug.out("Taken="+tup);
	      
        }
	      totaltime = System.currentTimeMillis() - starttime;
	      System.out.println(num +" Tuples taken(index query) from TS. Time : " + totaltime);
	
	
	      starttime = System.currentTimeMillis();
        Tuple template3 = new Tuple("Test3");
	      for (int i=0; i < num; i++) {
	      	
	      	ts.write("Test3");
	      	tup = ts.take(template3);
	      
	      }
	      totaltime = System.currentTimeMillis() - starttime;
	      System.out.println(num +" Tuples written/taken from TS. Time : " + totaltime);
	
	
	
	      System.out.println("That's all!");
        if (tsServer != null)   {
          tsServer.shutdown(10);
          Debug.out("Shutdown issued");
          do { 
            try { Thread.sleep(1000); } catch (Exception e) {}            
          } while (! tsServer.isShutdown());          
          System.exit(0);
        } else {
          TupleSpace.cleanup();
        }
       
    } catch(Exception e) {
        Debug.out(e);
    }

  }
}
/* 
** $Log: PerfTest1.java,v $
** Revision 2.1.2.2  2000/02/05 14:50:43  jthomas
** no message
**
** Revision 2.1.2.1  2000/01/28 18:18:43  jthomas
** Add item for testing non cloneable Fields
**
** Revision 2.1  1999/11/05 22:22:40  estesp
** Update revision number to 2.1 on all files
**
** Revision 1.1.1.1  1999/11/05 16:24:53  estesp
** Imported 2.1.0 release into Austin CVS
**
** Revision 1.9  1999/10/28 18:27:37  jthomas
** add usage info
**
** Revision 1.8  1999/10/06 01:12:17  jthomas
** cleanup documentation and some code
**
** Revision 1.7  1999/09/20 14:38:25  jthomas
** Add ability to choose nonPersistent and Local mode
**
** Revision 1.6  1999/09/08 15:31:37  jthomas
** Make the tests more self checking and easier to run
**
** Revision 1.5  1999/07/29 06:21:05  esakki
** *** empty log message ***
**
** Revision 1.4  1999/07/09 05:03:44  jthomas
** ?
**
*/